package com.ghp.admin.job.once;


import com.ghp.admin.service.InterfaceInfoService;
import com.ghp.admin.service.UserInterfaceInfoService;
import com.ghp.common.model.entity.InterfaceInfo;
import com.ghp.common.model.entity.UserInterfaceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ghp.common.constants.RedisConstants.INTERFACE_LEFT_NUM_KEY;
import static com.ghp.common.constants.RedisConstants.INTERFACE_PATH_METHOD_KEY;

/**
 * 全量同步数据到Redis
 *
 * @author ghp
 */
@Component
@Slf4j
//@Profile({"dev", "test"})
public class PreheatDataToRedis implements CommandLineRunner {

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 预热数据
     *
     * @param args
     */
    @Override
    public void run(String... args) {
        log.info("=============================Start:开始预热接口剩余调用次数=============================");
        List<UserInterfaceInfo> userInterfaceInfoList = userInterfaceInfoService.list();
        Map<String, Integer> leftNumMap = userInterfaceInfoList.stream().collect(Collectors.toMap(
                userInterfaceInfo -> userInterfaceInfo.getUserId() + "-" + userInterfaceInfo.getInterfaceInfoId(),
                UserInterfaceInfo::getLeftNum
        ));
        HashOperations<String, String, Integer> leftNumHashOps = redisTemplate.opsForHash();
        leftNumHashOps.putAll(INTERFACE_LEFT_NUM_KEY, leftNumMap);
        log.info("=============================End:成功预热接口剩余调用次数=============================");
        log.info("=============================Start:开始预热用户接口关系数据=============================");
        Map<String, Long> interfaceMap = interfaceInfoService.list().stream().collect(Collectors.toMap(
                interfaceInfo -> interfaceInfo.getUrl() + '-' + interfaceInfo.getMethod(),
                InterfaceInfo::getId
        ));
        HashOperations<String, String, Long> interfaceHashOps = redisTemplate.opsForHash();
        interfaceHashOps.putAll(INTERFACE_PATH_METHOD_KEY, interfaceMap);
        log.info("=============================End:成功预热用户接口关系数据=============================");
    }

}
